$(function() {
    initArtCateList();
    // 获取文章列表
    function initArtCateList() {
        $.ajax({
            type: "GET",
            url: "/my/article/cates",
            success: function(res) {
                var htmlStr = template("tmp_tbody", res);
                $("tbody").html(htmlStr)
            }
        });
    };
    // 为添加类别按钮添加点击事件
    var indexAdd;
    $("#btnAddCate").on("click", function() {
        indexAdd = layui.layer.open({
            type: 1,
            title: '添加文章类别',
            content: $("#dialog-add").html(),
            area: ['500px', '250px']
        })
    });
    //使用事件委托为form-add添加submit事件
    $("body").on("submit", "#form-add", function(e) {
        e.preventDefault()
        $.ajax({
            type: "POST",
            url: "/my/article/addcates",
            data: $(this).serialize(),
            success: function(res) {
                if (res.status !== 0) {
                    return layui.layer.msg("新增分类失败")
                }
                initArtCateList();
                layui.layer.msg("新增分类成功");
                layui.layer.close(indexAdd)
            }
        });
    });
    var indexEdit
        // 使用事件委托为btn-edit添加点击事件
    $("tbody").on("click", ".btn-edit", function() {
        indexEdit = layui.layer.open({
            type: 1,
            title: '添加文章分类',
            content: $("#dialog-edit").html(),
            area: ['500px', '250px']
        });
        var id = $(this).attr("data-id");
        $.ajax({
            type: "GET",
            url: "/my/article/cates/" + id,
            success: function(res) {
                layui.form.val("form-edit", res.data)
            }
        });
    });
    // 修改分类为表单添加事件
    $("body").on("submit", "#form-edit", function(e) {
        e.preventDefault()
        $.ajax({
            type: "POST",
            url: "/my/article/updatecate",
            data: $(this).serialize(),
            success: function(response) {
                if (response.status !== 0) {
                    return layui.layer.msg("更新分类信息失败！")
                }
                layui.layer.msg("更新分类信息成功！")
                initArtCateList();
                layui.layer.close(indexEdit)
            }
        });
    });
    $("tbody").on("click", ".btn-delete", function() {
        var id = $(this).attr("data-id");
        layui.layer.confirm('确认删除？', { icon: 3, title: '提示' }, function(index) {
            //do something
            $.ajax({
                type: "GET",
                url: "/my/article/deletecate/" + id,
                data: "data",
                success: function(response) {
                    if (response.status !== 0) {
                        return layui.layer.msg("删除分类失败！")
                    }
                    layui.layer.msg("删除分类成功！")
                    layer.close(index);
                    initArtCateList();
                }
            });
        });

    })
})